package com.cash.app.application

import android.app.Application
import android.content.Context
import android.os.Build.VERSION.SDK_INT
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.SingletonImageLoader
import coil3.disk.DiskCache
import coil3.disk.directory
import coil3.gif.AnimatedImageDecoder
import coil3.gif.GifDecoder
import coil3.memory.MemoryCache
import coil3.request.crossfade
import coil3.util.DebugLogger
import com.cash.app.BuildConfig
import com.cash.app.manager.GlobalTaskManager
import com.cash.app.utils.extra.ExtraInfoUtils

class MyApplication : Application(), SingletonImageLoader.Factory {
    companion object {
        lateinit var appContext: Context
    }

    override fun onCreate() {
        super.onCreate()
        appContext = applicationContext
        ActivityLifecycleManager.init(this)
        // Execute initialization
        AppInitializer.startInit(this)
    }

    // use Coil to load an image for the first time,it will be called.
    override fun newImageLoader(context: PlatformContext): ImageLoader {
        return ImageLoader.Builder(context)// Builder
            .crossfade(true)// Show fade
            .memoryCache {
                MemoryCache.Builder().maxSizePercent(context, percent = 0.3).build()
            } // memoryCache
            .diskCache { // diskCache
                DiskCache.Builder().directory(context.cacheDir.resolve("image_cache"))
                    .maxSizeBytes(512L * 1024 * 1024) // 512MB
                    .build()
            }// logger
            .apply {
                if (BuildConfig.DEBUG) {
                    logger(DebugLogger()) // Only add DebugLogger in debug builds
                }
            }.components {
                if (SDK_INT >= 28) {
                    add(AnimatedImageDecoder.Factory())
                } else {
                    add(GifDecoder.Factory())
                }
            }.build()
    }

    override fun onTerminate() {
        super.onTerminate()
        // Clean up coroutine resources
        GlobalTaskManager.cleanup()
        ExtraInfoUtils.removeBroadcast()
    }
}